<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>PHP data types</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PHP, learn PHP, data types, tutorial, programming language">
<meta name="description" content="In this part of the PHP tutorial, we cover PHP data types.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>PHP data types</h1>

<p>
In this part of the PHP tutorial, we will talk about data types. 
</p>

<p>
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients.
Tools to work with various data types are essential part of a modern computer language. 
According to the wikipedia definition, a <code>data type</code> is a set of values,
and the allowable operations on those values.
</p>

<div class="center">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* top_horizontal */
google_ad_slot = "3327173442";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
PHP has eight data types:
</p>

Scalar types
<ul>
<li>boolean</li>
<li>integer</li>
<li>float</li>
<li>string</li>
</ul>

Compound types
<ul>
<li>array</li>
<li>object</li>
</ul>

Special types
<ul>
<li>resources</li>
<li>NULL</li>
</ul>

<p>
Unlike in languages like Java, C or Visual Basic, in PHP you do not 
provide an explicit type definition for a variable. A variable's type 
is determined at runtime by PHP. If you assign a string to a variable, 
it becomes a string variable. Later if you assign an integer value,
the variable becomes an integer variable. 
</p>


<h2>Boolean values</h2>

<p>
There is a duality built in our world. There is a Heaven and Earth, 
water and fire, jing and jang, man and woman, love and hatred. In PHP the 
boolean data type is a primitive data type having one of two values: True or False. 
This is a fundamental data type. Very common in computer programs.
</p>

<p>
Happy parents are waiting a child to be born. They have chosen a name for both 
possibilities. If it is going to be a boy, they have chosen John. If it is going 
to be a girl, they have chosen Victoria. 
</p>

<pre class="code">
&lt;?php

$male = False;

$r = rand(0, 1);

$male = $r ? True: False;

if ($male) {
    echo "We will use name John\n";
} else {
    echo "We will use name Victoria\n";
}
?&gt;
</pre>

<p>
The script uses a random integer generator to simulate our case. 
</p>


<pre class="explanation">
$r = rand(0, 1);
</pre>

<p>
The <code>rand()</code> function returns a random number from 
the given integer boundaries. In our case 0 or 1. 
</p>

<pre class="explanation">
$male = $r ? True: False;
</pre>

<p>
We use the ternary operator to set a <code>$male</code> variable. The variable is
based on the random <code>$r</code> value. If $r equals to 1, the $male variable is 
set to True. If $r equals to 0, the $male variable is set to False. 
</p>


<pre class="explanation">
if ($male) {
    echo "We will use name John\n";
} else {
    echo "We will use name Victoria\n";
}
</pre>

<p>
We print the name. The if command works with boolean values. If the variable 
$male is True, we print the "We will use name John"
to the console. If it has a False value, we print the other string. 
</p>

<p>
The following script shows some common values that are considered to be True or False. 
For example, empty string, empty array, 0 are considered to be False.
</p>

<pre class="code">
&lt;?php
class Object {};

var_dump((bool) "");
var_dump((bool) 0);
var_dump((bool) -1);
var_dump((bool) "PHP");
var_dump((bool) array(32));
var_dump((bool) array());
var_dump((bool) "false");
var_dump((bool) new Object());
var_dump((bool) NULL);
?&gt;
</pre>

<p>
In this script, we inspect some values in a boolean context. 
The <code>var_dump()</code> function shows information about
a variable. The <code>(bool)</code> construct is called casting. 
In its casual context, the 0 value is a number. In a boolean context, it is
False. The boolean context is when we use (bool) casting, when we use certain 
operators (negation, comparison operators)
and when we use if/else, while keywords. 
</p>

<pre>
$ php boolean.php
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
</pre>

<p>
Here is the outcome of the script. 
</p>


<h2>Integers</h2>

<p>
Integers are a subset of the real numbers. They are written without a 
fraction or a decimal component. 
Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...}
Integers are infinite. 
</p>

<p>
In computer languages, integers are primitive data types. Computers can 
practically work only with a subset of integer values, because computers 
have finite capacity. Integers are used to count discrete
entities. We can have 3, 4, 6 humans, but we cannot have 3.33 humans. 
We can have 3.33 kilograms.
</p>

<p>
Integers can be specified in three different <b>notations</b> in PHP. Decimal, 
hexadecimal and octal. Octal values are preceded by 0, hexadecimal by 0x.
</p>

<pre class="code">
&lt;?php

$var1 = 31;
$var2 = 031;
$var3 = 0x31;

echo "$var1\n";
echo "$var2\n";
echo "$var3\n";

?&gt;
</pre>

<p>
We assign 31 to three variables using three notations. And we print them to the console.
</p>

<pre>
$ php notation.php 
31
25
49
</pre>

<p>
The default notation is the decimal. The script shows these three numbers in decimal. 
</p>


<p>
Integers in PHP have a <b>fixed maximum size</b>. The size of integers is platform dependent. 
PHP has built-in constants to show the maximum size of an integer. 
</p>

<pre class="code">
$ uname -mo
i686 GNU/Linux
$ php -a
Interactive shell

php > echo PHP_INT_SIZE;
4
php > echo PHP_INT_MAX;
2147483647
php > 
</pre>

<p>
On my 32bit Ubuntu system, an integer value size is four bytes. The maximum integer
value is 2147483647.
</p>

<p>
In Java and C, if an integer value is bigger than the maximum value allowed, integer overflow
happens. PHP works differently. In PHP, the integer becomes a float number. Floating point numbers
have greater boundaries.
</p>

<pre class="code">
&lt;?php

$var = PHP_INT_MAX;

echo var_dump($var);
$var++;
echo var_dump($var);

?&gt;
</pre>

<p>
We assign a maximum integer value to the $var variable. We increase the variable by one.
And we compare the contents.
</p>

<pre class="code">
$ php boundary.php 
int(2147483647)
float(2147483648)
</pre>

<p>
As we have mentioned previously, internally, the number becomes a floating point value.
</p>

<p>
In Java, the value after increasing would be -2147483648. This is where the term
integer overflow comes from. The number goes over the top and becomes the smallest negative
integer value assignable to a variable.  
</p>

<p>
If we work with integers, we deal with discrete entities. We would use integers to count apples. 
</p>

<pre class="code">
&lt;?php

# number of baskets
$baskets = 16;

# number of apples in each basket 
$apples_in_basket = 24;

# total number of apples
$total = $baskets * $apples_in_basket;

echo "There are total of $total apples \n";
?&gt;
</pre>


<p>
In our script, we count the total amount of apples. We use the multiplication operation. 
</p>

<pre>
$ php apples.php 
There are total of 384 apples 
</pre>

<p>
The output of the script. 
</p>


<h2>Floating point numbers</h2>

<p>
Floating point numbers represent real numbers in computing. Real numbers measure 
continuous quantities. Like weight, height or speed. Floating point numbers in PHP can be larger 
than integers and they can have a decimal point. The size of a float is platform dependent. 
</p>

<p>
We can use various syntax to create floating point values.
</p>

<pre class="code">
&lt;?php

$a = 1.245;
$b = 1.2e3;
$c = 2E-10;
$d = 1264275425335735;

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);

?&gt;
</pre>

<p>
In this example, we have two cases of notations, that are used by scientists
to denote floating point values. Also the $d variable is assigned a large number, 
so it is automatically converted to float type. 
</p>

<pre>
$ php floats.php 
float(1.245)
float(1200)
float(2.0E-10)
float(1264275425340000)
</pre>

<p>
This is the output of the above script. 
</p>

<p>
According to the documentation, floating point numbers should not be tested for equality. 
We will show an example why. 
</p>

<pre class="code">
$ php -a
Interactive shell

php &gt; echo 1/3;
0.333333333333
php &gt; $var = (0.333333333333 == 1/3);
php &gt; var_dump($var);
bool(false)
php &gt; 
</pre>

<p>
In this example, we compare two values that seem to be identical. But
they yield unexpected result. 
</p>

<p>
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
</p>

<pre class="code">
&lt;?php

# 100m is 0.1 km

$distance = 0.1;

# 9.87s is 9.87/60*60 h

$time = 9.87 / 3600;

$speed = $distance / $time;

echo "The average speed of a sprinter is $speed \n";

?&gt;
</pre>

<p>
In this example, it is necessary to use floating point values. 
</p>

<pre class="explanation">
$speed = $distance / $time;
</pre>

<p>
To get the speed, we divide the distance by the time. 
</p>


<pre>
$ php sprinter.php 
The average speed of a sprinter is 36.4741641337 
</pre>

<p>
This is the output of the sprinter script. 36.4741641337 is a floating point number.
</p>


<h2>Strings</h2>

<p>
<code>String</code> is a data type representing textual data in computer programs. 
Probably the single most important data type in programming. 
</p>

<p>
Since string are very important in every programming language, we will dedicate 
a whole chapter to them. Here we only drop a small example. 
</p>

<pre class="code">
&lt;?php

$a = "PHP ";
$b = 'PERL';

echo $a, $b;
echo "\n";

?&gt;
</pre>

<p>
We can use single quotes and double quotes to create string literals. 
</p>

<pre>
$ php strings.php 
PHP PERL
</pre>

<p>
The script outputs two strings to the console. The \n is a special sequence, a new line.
The effect of this character is like if you hit the enter key when typing text. 
</p>

<h2>Arrays</h2>

<p>
Array is a complex data type which handles a collection of elements. Each of the elements can be
accessed by an index. In PHP, arrays are more diverse. Arrays can be treated as arrays, lists or dictionaries. 
In other words, arrays are all what in other languages we call arrays, lists, dictionaries.  
</p>

<p>
Because collections are very important in all computer languages, we dedicate 
two chapters to collections - arrays. Here we show only a small example. 
</p>


<pre class="code">
&lt;?php

$names = array("Jane", "Lucy", "Timea", "Beky", "Lenka");

print_r($names);

?&gt;
</pre>

<p>
The <code>array</code> keyword is used to create a collection of elements. In our case we
have names. The <code>print_r</code> function prints a human readable information about a 
variable to the console. 
</p>

<pre>
$ php init.php 
Array
(
    [0] => Jane
    [1] => Lucy
    [2] => Timea
    [3] => Beky
    [4] => Lenka
)
</pre>

<p>
Output of the script. The numbers are indeces by which we can access the names. 
</p>


<h2>Objects</h2>

<p>
So far, we have been talking about built-in data types. Objects are user defined data types. 
Programmers can create their data types that fit their domain. More about objects in chapter about
object oriented programming, OOP.
</p>

<h2>Resources</h2>

<p>
Resources are special data types. They hold a reference to an external resource. They are created
by special functions. Resources are handlers to opened files, database connections or image canvas areas.
</p>


<h2>NULL</h2>

<p>
There is another special data type - <code>NULL</code>. Basically, the data type means non existent, 
not known or empty. 
</p>

<p>
In PHP, a variable is NULL in three cases:
</p>

<ul>
<li>it was not assigned a value</li>
<li>it was assigned a special NULL constant</li>
<li>it was unset with the unset() function</li>
</ul>

<pre class="code">
&lt;?php

$a;
$b = NULL;

$c = 1;
unset($c);

$d = 2;

if (is_null($a)) echo "\$a is null\n";
if (is_null($b)) echo "\$b is null\n";
if (is_null($c)) echo "\$c is null\n";
if (is_null($d)) echo "\$d is null\n";

?&gt;
</pre>

<p>
In our example, we have four variables. Three of them are considered to be NULL. 
We use the <code>is_null()</code> function to determine, if the variable
is NULL. 
</p>

<pre>
$ php null.php 
$a is null
$b is null
$c is null
</pre>

<p>
Outcome of the script. 
</p>

<h2>Type casting</h2>

<p>
We often work with multiple data types at once. Converting one data type to another one is a common
job in programming.
<b>Type conversion</b> or <b>typecasting</b> refers to changing an entity of one data type into another.
There are two types of conversion. Implicit and explicit. Implicit type conversion, also known as coercion,
is an automatic type conversion by the compiler. 
</p>

<pre class="code">
php &gt; echo "45" + 12;
57
php &gt; echo 12 + 12.4;
24.4
</pre>

<p>
In the above example, we have two examples of implicit type casting. In the first statement, the
string is converted to integer and added to the second operand. 
If either operand is a float, then both operands are evaluated as floats, 
and the result will be a float.
</p>

<p>
Explicit conversion happens, when we use the cast constructs, like (boolean). 
</p>

<pre class="code">
php &gt; $a = 12.43;
php &gt; var_dump($a);
float(12.43)
php &gt; $a = (integer) $a;
php &gt; var_dump($a);
int(12)
php &gt; $a = (string) $a;
php &gt; var_dump($a);
string(2) "12"
php &gt; $a = (boolean) $a;
php &gt; var_dump($a);
bool(true)
</pre>

<p>
This code snippet shows explicit casting in action. First we assign a float value
to a variable. Later we cast it to integer, string and finally boolean data type. 
</p>


<p>
In this part of the PHP tutorial, we covered data types. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>



<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 7, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

